package main

import (
	"cps-user/model/global"
	"cps-user/security"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func main() {
	r := gin.Default()
	r.Use(global.Load())             // 加载配置文件
	r.Use(security.Load())           // 加载模块
	r.Use(security.LoginIntercept()) // 加载拦截器

	r.GET("/login", func(c *gin.Context) {
		name := c.Query("name")

		s, _ := security.SessionManager.New(c.Request, global.GlobalConfig.SessionKey)
		s.Values["user"] = name
		if err := security.SessionManager.Save(c.Request, c.Writer, s); err != nil {
			log.Fatal(err)
		}

		c.JSON(200, gin.H{
			"登录": name,
		})
	})

	r.GET("/logout", func(c *gin.Context) {
		name := c.Query("name")

		s, err := security.SessionManager.Get(c.Request, global.GlobalConfig.SessionKey)
		if err != nil {
			log.Fatal(err)
		}
		logoutName := s.Values["user"].(string)

		s.Options.MaxAge = -1
		if err := s.Save(c.Request, c.Writer); err != nil {
			log.Fatal(err)
		}
		fmt.Println(name + "退出了")
		c.JSON(200, "注销 "+logoutName)
	})

	r.Run("0.0.0.0:9999") // listen and serve on 0.0.0.0:8080
}
